class Solution {
public:
    vector<vector<int>> v;
    bool flag[9];
    vector<int> path;
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        dfs(nums);
        return v;
    }
    void dfs(vector<int>& nums) {
        if (path.size() == nums.size()) {
            v.push_back(path);
            return;
        }
        for (int i = 0; i < nums.size(); i++) {
            if (flag[i] == true || (i != 0 && nums[i] == nums[i - 1] && flag[i - 1] == false))
                continue;
            if (flag[i] == false && (i == 0 || nums[i] != nums[i - 1] || flag[i - 1] == true)) {
                path.push_back(nums[i]);
                flag[i] = true;
                dfs(nums);
                path.pop_back();
                flag[i] = false;
            }
        }
    }
};
class Solution {
public:
    vector<string> ret;
    string path;
    int left = 0;
    int right = 0;
    int count;
    vector<string> generateParenthesis(int n) {
        count = 2 * n;
        dfs();
        return ret;
    }
    void dfs()
    {
        if (right > left || left > count / 2) return;
        if (path.size() == count)
        {
            ret.push_back(path);
            return;
        }
        path += '(';
        left++;
        dfs();
        path.pop_back();
        left--;
        path += ')';
        right++;
        dfs();
        right--;
        path.pop_back();
    }
};
class Solution {
public:
    vector<vector<int>> ret;
    vector<int> path;
    vector<vector<int>> combine(int n, int k) {
        dfs(1, n, k);
        return ret;
    }
    void dfs(int i, int n, int k)
    {
        if (path.size() == k)
        {
            ret.push_back(path);
            return;
        }
        for (int x = i; x <= n; x++)
        {
            path.push_back(x);
            dfs(x + 1, n, k);
            path.pop_back();
        }
    }
};
